package top.h1234.web;

import top.h1234.pojo.User;
import top.h1234.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {

    // 获取service对象
    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收用户名、密码、验证码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");

        // 封装对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        // 判断验证码是否正确
        // 获取session域中存储的生成的验证码
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");

        // 填写的验证码与生成的验证码不一致
        if (!checkCodeGen.equalsIgnoreCase(checkCode)) {
            request.setAttribute("checkCode_msg", "验证码错误");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }

        // 调用service
        boolean flag = service.register(user);

        // 判断是否注册成功
        if (flag) {
            // 注册成功，跳转到登录页
            request.setAttribute("register_msg", "注册成功，请登录！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } else {
            // 注册失败，跳回注册页
            request.setAttribute("register_msg", "用户名已存在！");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
